from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.text import slugify
from django.urls import reverse
# Create your models here.

class Image(models.Model):
    user = models.ForeignKey(User, related_name='images_created', on_delete=models.CASCADE)
    title = models.CharField(max_length=200, verbose_name='标题')
    slug = models.SlugField(max_length=200, blank=True, verbose_name='标签')
    url = models.URLField(verbose_name='图片源 URL')
    image = models.ImageField(upload_to='images/%Y/%m/%d', verbose_name='图片文件')
    description = models.TextField(blank=True, verbose_name='描述')
    user_like = models.ManyToManyField(User,related_name='images_liked',blank=True)
    created = models.DateTimeField(auto_now_add=True, db_index=True)    #我们使用了 db_index=True ，所以 Django 将会在数据库
                                                                        # 中为这个字段创建索引

    class Meta:
        verbose_name = "图像"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
            super(Image, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('images:detail', args=(self.id, self.slug))

"""
在这段代码中，我们使用了 Django 提供的slugify()函数在没有提供
slug字段时根据给定的图片标题自动生slug,然后，我们保存了这个对
象。我们自动生成slug，这样的话用户就不用自己输入slug字段了
"""

